import React, { Component } from "react";

import { Form, Input, Table, Button, Divider,Row,Col ,Select, DatePicker, Modal, InputNumber} from "antd";
import Content from "../../components/Content/Content";

const { Item } = Form;
const data = [];
for (let i = 0; i < 6; i++) {
  data.push({
    key: i.toString(),
    name: `Edrward ${i}`,
    age: 32,
    address: `London Park no. ${i}`
  });
}
const EditableContext = React.createContext();

class EditableCell extends React.Component {
  getInput = () => {
    if (this.props.inputType === "number") {
      return <InputNumber />;
    }
    return <Input />;
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0, width: "200%" }}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: true,
                  message: `Please Input ${title}!`
                }
              ],
              initialValue: record[dataIndex]
            })(this.getInput())}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return (
      <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
    );
  }
}

class EditableTable extends Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedRowKeys: [], // Check here to configure the default column

      dataSource: data, 
      count: 1,

      asdyp_type:'', // 样品编号类型

      viewData: {},
      newData: {},
      searchParams : {},

      loading_out: false,
      loading_search: false,

      pageNum: 1,
      pageSize: 100
    };

    this.columns = [
      {
        title: "编号",
        dataIndex: "ID",
        fixed: "left",
        width: 200,
      },
      {
        title: "初选报告编号",
        dataIndex: "as_id",
      },
      {
        title: "初筛样品编号",
        dataIndex: "yp_id",
      },
      {
        title: "筛选菌株编号",
        dataIndex: "sxjj_id",
      },
      {
        title: "分离编号待定",
        dataIndex: "as_ysflid",
      },
      {
        title: "初检编号待定",
        dataIndex: "info_cjid",

      },
      {
        title: "类别",
        dataIndex: "as_type",

      },
      {
        title: "近缘",
        dataIndex: "info_jyjz",

      },
      {
        title: "培养基",
        dataIndex: "as_fjpyj",
      },
      {
        title: "状况",
        dataIndex: "f_zk",
      },
      {
        title: "颜色",
        dataIndex: "f_ys",
      },
      {
        title: "批号",
        dataIndex: "as_ph",
      },
      {
        title: "信息",
        dataIndex: "info_info",
      },
      {
        title: "模型方法",
        dataIndex: "as_mxff",
      },
      {
        title: "传代培养基",
        dataIndex: "as_cdpyj",
      },
      {
        title: "生长状况",
        dataIndex: "f_szzk",
      },
      {
        title: "孢子",
        dataIndex: "info_bzyw",
      },
      {
        title: "正面颜色",
        dataIndex: "info_zmys",
      },
      {
        title: "反面颜色",
        dataIndex: "info_fmys",
      },
      {
        title: "	色素",
        dataIndex: "info_css",
      }
    ];
  }

  start = () => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false,
      });
    }, 1000);
  };

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  isEditing = record => record.id === this.state.editingKey;

  cancel = () => {
    this.setState({ editingKey: "" });
  };

  save(form, id) {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const newData = [...this.state.dataSource];
      const index = newData.findIndex(item => id === item.id);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row
        });
        this.setState({ dataSource: newData, editingKey: "" });
      } else {
        newData.push(row);
        this.setState({ dataSource: newData, editingKey: "" });
      }
    });
  }

  edit(id) {
    this.setState({ editingKey: id });
  }
  
  
  loadData = (current = 1) => {

    this.setState({ loading_search: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading_search: false
      });
    }, 1000);
    
    const url = global.api.activityscreeningReport + '?as_id=' + (this.state.searchParams.as_id || "") + '&sxjj_id=' + (this.state.searchParams.sxjj_id||"");

    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize, search:{}})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count, newData: {}})
    })
    .catch(err => {
      Modal.error({
        content: '数据加载失败！'
      })
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  }

  // 导出到本地
  outToLocal = () => {
    this.setState({ loading_out: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading_out: false
      });
    }, 1000);

    let selectedRowKeys = this.state.selectedRowKeys;
    if(selectedRowKeys) {
      for( let x of selectedRowKeys ) {
        let record = this.state.dataSource[x];
        let id = record.id;
        // TODO 跳转到导出URL
      }
    }   
 
  };

  render() {
    const components = {
      body: {
        cell: EditableCell
      }
    };
    const { loading_out, loading_search, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === "age" ? "number" : "text",
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record)
        })
      };
    });

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 9 }
      }
    };

    return (
      <Content>
        <Form
          {...formItemLayout}
          onSubmit={this.onSubmit}
          colon={false}
          style={{ borderBottom: "20px solid #f0f2f5" }}
        >
          <Item label="启动编号">
                <Input onChange={e => this.state.searchParams.as_id  = e.target.value } />
          </Item>
          <Item label="筛选菌株编号">
                <Input onChange={e => this.state.searchParams.sxjj_id  = e.target.value } />
          </Item>
          <Item wrapperCol={{ span: 10, offset: 3 }}>
          <Button type="primary" htmlType="submit" onClick={() => this.loadData(1)} loading={loading_search}>
              查询
            </Button>
          </Item>
        </Form>
        <Button type="primary" htmlType="submit" style={{marginLeft:'24px', marginTop: '20px'}} onClick={this.outToLocal} disabled={!hasSelected} loading={loading_out}>
          导出
        </Button>
        <span style={{ marginLeft: 8 }}>
            {hasSelected ? `选中 ${selectedRowKeys.length} 条` : ''}
          </span>
        <EditableContext.Provider value={this.props.form}>
          <Table
          rowSelection={rowSelection}
            components={components}
            bordered
            dataSource={this.state.dataSource}
            columns={columns}
            rowClassName="editable-row"
            pagination={{
              onChange: this.cancel
            }}
            scroll={{ x: 3000 }}
          />
        </EditableContext.Provider>
      </Content>
    );
  }
}

const PrimaryRecord = Form.create()(EditableTable);
export default PrimaryRecord; 
